<template>
  <div class="review-container">
    <back-header :titleSize="16" :titleBold="false" :title="getTitle">
      <template #icon>
        <van-icon name="completed-o" size="24" />
      </template>
    </back-header>
    <div style="height: 56px"></div>
    <div class="content">
      <div class="filter-container">
        <van-calendar
          v-model:show="showCalendar"
          type="range"
          @confirm="onConfirm"
          :min-date="minDate"
          :max-date="maxDate"
        />
        <van-cell
          title="选择时间范围"
          :value="formatDateRange"
          is-link
          @click="showCalendar = true"
          class="date-selector"
        />
      </div>

      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="getList"
        class="review-list"
      >
        <van-cell
          v-for="item in tables"
          :key="item.selfTestId"
          class="review-item"
        >
          <template #title>
            <div class="cell-title">
              <span class="username">用时：{{ item.usedTime }}</span>
              <span class="score">{{ item.score }}分</span>
            </div>
          </template>
          <template #label>
            <div class="cell-label">
              <div class="info-wrapper">
                <span
                  >考试时间：<em>{{
                    item.createTime?.replace("T", " ")
                  }}</em></span
                >
              </div>
              <van-button
                type="primary"
                size="small"
                class="detail-btn"
                @click="handleDetail(item.selfTestId)"
              >
                查看
              </van-button>
            </div>
          </template>
        </van-cell>
      </van-list>
    </div>
  </div>
</template>

<script setup>
import BackHeader from "@/components/common/BackHeader.vue";
import { ref, computed, onMounted } from "vue";
import selfTestResult from "@/api/selfTest/selfTestResult";
import { useRoute, useRouter } from "vue-router";
import { showToast } from "vant";
import { useStore } from "vuex";

const store = useStore();
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const finished = ref(false);
const tables = ref([]);
const showCalendar = ref(false);
const currentPage = ref(1);
let pageSize = 10;

const getTitle = computed(() => {
  if (store.getters.selectValue) {
    const index = store.getters.selectValue.indexOf("/");
    if (index != -1) {
      const arr = store.getters.selectValue.split("/");
      return "自测回顾:" + arr[1];
    } else {
      return "自测回顾:" + store.getters.selectValue;
    }
  } else {
    return "自测回顾";
  }
});

// Calendar related
const minDate = new Date(2020, 0, 1);
const maxDate = new Date();
const timeRange = ref([]);
const startTime = ref("");
const endTime = ref("");

const formatDateRange = computed(() => {
  if (startTime.value && endTime.value) {
    return `${startTime.value} 至 ${endTime.value}`;
  }
  return "请选择日期范围";
});

const onConfirm = (dates) => {
  const [start, end] = dates;
  startTime.value = formatDate(start);
  endTime.value = formatDate(end);
  showCalendar.value = false;
  currentPage.value = 1;
  tables.value = [];
  finished.value = false;
  getList();
};

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

const handleDetail = (selfTestId) => {

  router.push({
    path: "/test/answer",
    query: { selfTestId, title: getTitle.value },
  });
};

const getList = async () => {
  try {
    loading.value = true;
    const res = await selfTestResult.getList(
      route.query.selectedId,
      currentPage.value,
      pageSize,
      startTime.value,
      endTime.value
    );

    if (currentPage.value === 1) {
      tables.value = res.data;
    } else {
      tables.value = [...tables.value, ...res.data];
    }

    const totalRes = await selfTestResult.getTotal(
      route.query.selectedId,
      startTime.value,
      endTime.value
    );

    const totalPages = Math.ceil(totalRes.data / pageSize);
    if (currentPage.value >= totalPages) {
      finished.value = true;
    } else {
      currentPage.value += 1;
    }
  } catch (error) {
    console.error("Error fetching data:", error);
    showToast("获取数据失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.review-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  display: flex;
  flex-direction: column;
}

.content {
  flex: 1;
  padding: 12px;
  background-color: #f7f8fa;
}

.filter-container {
  margin-bottom: 12px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.date-selector {
  background: #fff;
  margin-bottom: 8px;
}

.review-list {
  border-radius: 8px;
  overflow: hidden;
}

.review-item {
  margin-bottom: 8px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.cell-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.username {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}

.score {
  font-size: 18px;
  font-weight: 600;
  color: #07c160;
}

.cell-label {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  font-size: 13px;
  color: #969799;
  margin-top: 8px;
}

.info-wrapper {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-btn {
  border-radius: 15px;
  font-size: 13px;
  padding: 0 12px;
  height: 28px;
  margin-left: 12px;
  flex-shrink: 0;
}

@media (prefers-color-scheme: dark) {
  .review-container,
  .content {
    background-color: #121212;
  }

  .review-item,
  .date-selector {
    background-color: #1c1c1c;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  }

  .username {
    color: #e5e5e5;
  }

  .score {
    color: #07c160;
  }

  .cell-label {
    color: #888;
  }

  .cell-label em {
    color: #aaa;
  }
}
</style>
